package cn.wenhe9.yygh.sms.controller;

import cn.wenhe9.yygh.common.result.ResultResponse;
import cn.wenhe9.yygh.sms.service.SmsService;
import cn.wenhe9.yygh.sms.utils.ConstantPropertiesUtils;
import cn.wenhe9.yygh.sms.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author DuJinliang
 * 2022/4/5
 */
@Api(tags = "短信接口")
@RestController
@RequestMapping("/api/sms")
public class SmsApiController {

    @Resource
    private SmsService smsService;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 发送手机验证码
     * @param phone String
     * @return ResultResponse
     */
    @ApiOperation("发送手机验证码")
    @GetMapping("/send/{phone}")
    public ResultResponse sendCode(@PathVariable(name = "phone") String phone){
        //从redis获取验证码 如果获取到 返回ok
        //key 手机号 value 验证码
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)){
            return ResultResponse.ok();
        }
        //如果中redis获取不到
        //生成验证码 通过整合短信服务进行发送
        code = RandomUtil.getSixBitRandom();
        //调用service通过整合短信服务进行发送
        boolean isSend =  smsService.send(phone, code);
        //生成验证码放到redis里面,设置有效时间
        if (isSend){
            redisTemplate.opsForValue().set(phone, code, ConstantPropertiesUtils.TIMEOUT, TimeUnit.MINUTES);
            return ResultResponse.ok();
        }
        return ResultResponse.fail().message("发送短信失败");
    }

}
